import { User } from "../db/sequelize.js"
import { Op } from 'sequelize'
function fn_listAll() {
    return async (ctx, next) => {
        ctx.body = await User.findAll()
    }
}
function fn_listById() {
    return async (ctx, next) => {
        let uId = ctx.params.id
        ctx.body = await User.findByPk(uId)
    }
}
function fn_add() {
    return async (ctx, next) => {
        ctx.body = '222'
        let uId = ctx.params.id
        let user = ctx.request.body
        await User.create(user, {
            where: {
                id: uId
            }
        })
    }
}
function fn_listByKey() {
    return async (ctx, next) => {
        let keyWord = ctx.params.key
        ctx.body = await User.findAll({
            where: [{
                [Op.or]: {
                    name: {
                        [Op.like]: `%${keyWord}%`
                    }
                }
            }]
        })
    }
}
function fn_update() {
    return async (ctx, next) => {
        ctx.body=''
        let uId = ctx.params.id
        let user = ctx.request.body
        console.log(user);
        
        await User.update(user, {
            where: {
                id: uId
            }
        })

    }
}
function fn_delete() {
    return async (ctx, next) => {
        ctx.body = '222'
        let uId = ctx.params.id
        await User.destroy({
            where: {
                id: uId
            }
        })
    }
}

export var user = {
    'get /users': fn_listAll(),
    'get /user/:id': fn_listById(),
    'get /users/:key': fn_listByKey(),
    'post /user': fn_add(),
    'put /user/:id': fn_update(),
    'delete /user/:id': fn_delete()
}